package com.paas.form.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.paas.common.model.RestResponse;
import com.paas.common.page.PageBean;
import com.paas.common.token.TokenModel;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.controller.BaseController;
import com.paas.form.entity.FormAttributePubEntity;
import com.paas.form.entity.FormViewPubEntity;
import com.paas.form.queue.FormApilogProducter;
import com.paas.form.service.IFormAttributePubService;
import com.paas.form.service.IFormViewPubService;
import com.paas.form.vo.FormApiStatus;
import com.paas.plus.tool.form.model.*;
import com.paas.plus.tool.form.server.FormServer;
import com.paas.plus.tool.form.server.FormService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;


@Slf4j
@RestController
@RequestMapping(value = "/apis/form")
public class FormApiController  extends BaseController {


    @Autowired
    public FormServer formServer;


    @Autowired
    public FormService formService;

    @Autowired
    public FormApilogProducter formApiProducter;

    //定版视图
    @Autowired
    public IFormViewPubService formViewPubService;

    //定版属性
    @Autowired
    public IFormAttributePubService formAttributePubService;


    /**
     * 查询主数据模型的表单定义
     * @param req
     * @param viewId
     * @return
     */
    @GetMapping(value = "/queryFormdefs")
    @ResponseBody
    public RestResponse queryFormdefs(HttpServletRequest req, String viewId){

        log.info("viewId:"+viewId);
        return null;
    }

    private JSONObject getAllRequestParam(final HttpServletRequest request) {
        JSONObject params = new JSONObject();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                params.put(en, value);
            }
        }
        return params;
    }

    /**
     * 主数据分页查询接口，根据主数据模型id、主数据name查询多条条主数据信息
     * @param req
     * @param viewId
     * @param viewName
     * @param pageSize
     * @param currentPage
     * @return
     */
    @GetMapping(value = "/queryPageMasterData")
    @ResponseBody
    public RestResponse queryPageMasterData(HttpServletRequest req, String viewId, String viewName,Integer currentPage, Integer pageSize){
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null || (pageSize > 100) || (pageSize < 0)) {
            pageSize = 100;
        }
        QueryListVo queryListVo = new QueryListVo();
        queryListVo.setCurrentPage(currentPage);
        queryListVo.setPageSize(pageSize);

        if(StringUtil.isNotEmpty(viewId)){
            //使用viewId
            queryListVo.setViewId(viewId);
        }else if(StringUtil.isNotEmpty(viewName)){
            //使用viewName
            QueryWrapper<FormViewPubEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name",viewName);
            FormViewPubEntity formViewPubBean = formViewPubService.getOne(queryWrapper);
            if(BeanUtil.isNotEmpty(formViewPubBean)){
                queryListVo.setViewId(formViewPubBean.getId());
            }else {
                return RestResponse.error("不存在viewName对应的视图");
            }
        }else {
            return RestResponse.error("viewId和viewName均为空");
        }
        //查询视图的属性
        FormAttributePubEntity Attribute = new FormAttributePubEntity();
        Attribute.setStatus(SystemConst.NORMAL_STATUS);
        Attribute.setViewId(queryListVo.getViewId());
        List<FormAttributePubEntity>  attributeList =formAttributePubService.getList(Attribute);
        if(BeanUtil.isEmpty(attributeList) || attributeList.size()==0){
            return RestResponse.error("当前视图没有配置属性,请联系维护人员");
        }
        List<Column> columns=new ArrayList<>();
        for (FormAttributePubEntity attribute:attributeList) {
            Column column=new Column();
            column.setCode(attribute.getCode());
            column.setName(attribute.getName());
            column.setDataType(attribute.getDataType());
            columns.add(column);

        }
        queryListVo.setColumn(columns);
        //查询数据
        PageBean<Map<String,Object>> pageBean=formServer.getPageList(queryListVo);
        return RestResponse.success().put("pageBean",pageBean);
    }


    /**
     * 主数据查询接口，根据主数据模型id、主数据id查询一条主数据详细信息
     * @param req
     * @param viewId
     * @param dataId
     * @return
     */
    @GetMapping(value = "/queryMasterData")
    @ResponseBody
    public RestResponse queryMasterData(HttpServletRequest req, String viewId, String dataId){
        TokenModel tokenModel = getTokenModel();
        ApiLog apiLog = new ApiLog();
        apiLog.setViewId(viewId);
        apiLog.setDataId(dataId);
        apiLog.setType("1");
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiLog.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        JSONObject params =getAllRequestParam(req);
        apiLog.setJsonObject(params);
        Date startDate = new Date();
        apiLog.setStartDate(startDate);

        //定义返回数据
        RestResponse resultRestResponse = null;
        try{
            //先根据ViewId查视图对象
            FormViewPubEntity formViewEntity=formViewPubService.getById(viewId);

            if(BeanUtil.isEmpty(formViewEntity) || StringUtil.isEmpty(formViewEntity.getId())){
                apiLog.setCallStatus("0");
                apiLog.setError("无效的视图id,请检查输入参数");
                return RestResponse.error("无效的视图id,请检查输入参数");
            }

            //查询视图的属性
            FormAttributePubEntity Attribute=new FormAttributePubEntity();
            Attribute.setStatus(SystemConst.NORMAL_STATUS);
            Attribute.setViewId(viewId);
            List<FormAttributePubEntity>  attributeList =formAttributePubService.getList(Attribute);
            if(BeanUtil.isEmpty(attributeList) || attributeList.size()==0){
                apiLog.setCallStatus("0");
                apiLog.setError("当前视图没有配置属性,请联系维护人员");
                return RestResponse.error("当前视图没有配置属性,请联系维护人员");
            }

            List<Column> columns=new ArrayList<>();
            QueryListVo queryListVo=new QueryListVo();
            queryListVo.setPageSize(10);
            queryListVo.setCurrentPage(1);
            queryListVo.setViewId(viewId);
            for (FormAttributePubEntity attribute:attributeList) {
                Column column=new Column();
                column.setCode(attribute.getCode());
                column.setName(attribute.getName());
                column.setDataType("string");
                columns.add(column);

            }
            queryListVo.setColumn(columns);
            //查询条件
            Criteria criteria=new Criteria();
            criteria.setCode(formViewEntity.getIdField());
            criteria.setName(formViewEntity.getIdField());
            criteria.setDataType("input");
            criteria.setValue(dataId);
            List<Criteria> criteriaList=new ArrayList<>();
            criteriaList.add(criteria);
            queryListVo.setCriteria(criteriaList);
            //查询数据
            PageBean<Map<String,Object>> pageBean=formServer.getPageList(queryListVo);
            if(BeanUtil.isEmpty(pageBean) || BeanUtil.isEmpty(pageBean.getData()) ||pageBean.getData().size()==0 ){
                //返回空数据
                //设置接口调用成功
                apiLog.setCallStatus("1");
                resultRestResponse =  RestResponse.success().put("jsonData",new JSONObject());
            }else{
                //获取主视图数据
                Map masterViewData=pageBean.getData().get(0);
                //查询子视图
                FormViewPubEntity formViewPubEntity=new FormViewPubEntity();
                formViewPubEntity.setStatus(SystemConst.NORMAL_STATUS);
                formViewPubEntity.setViewId(viewId);
                List<FormViewPubEntity> childViewlist = formViewPubService.getList(formViewPubEntity);
                if(childViewlist.size()>0){
                    //子视图属性map
                    Map<String,List<FormAttributePubEntity>> childAttributeMap=new HashMap<>();
                    //子列表数据
                    Map<String,List<Map<String,Object>>> childListDataMap=new HashMap<>();
                    for (int i = 0; i <childViewlist.size() ; i++) {
                        FormAttributePubEntity childAttribute=new FormAttributePubEntity();
                        childAttribute.setStatus(SystemConst.NORMAL_STATUS);
                        childAttribute.setViewId(childViewlist.get(i).getId());
                        List<FormAttributePubEntity>  childAttributes =formAttributePubService.getList(childAttribute);
                        if(childAttributes.size()>0){
                            childAttributeMap.put(childViewlist.get(i).getId(),childAttributes);

                            List<Column> childColumns=new ArrayList<>();
                            QueryListVo querychildListVo=new QueryListVo();
                            querychildListVo.setPageSize(100);
                            querychildListVo.setCurrentPage(1);
                            querychildListVo.setViewId(childViewlist.get(i).getId());
                            for (FormAttributePubEntity attribute:childAttributes) {
                                Column column=new Column();
                                column.setCode(attribute.getCode());
                                column.setName(attribute.getName());
                                column.setDataType("string");
                                childColumns.add(column);
                            }
                            querychildListVo.setColumn(childColumns);
                            //查询条件
                            Criteria childCriteria=new Criteria();
                            childCriteria.setCode(childViewlist.get(i).getForeignKeyMapping());
                            childCriteria.setName(childViewlist.get(i).getForeignKeyMapping());
                            childCriteria.setDataType("string");
                            childCriteria.setValue(dataId);
                            List<Criteria> childCriteriaList=new ArrayList<>();
                            childCriteriaList.add(childCriteria);
                            querychildListVo.setCriteria(childCriteriaList);

                            PageBean<Map<String,Object>> childPageBean=formServer.getPageList(querychildListVo);
                            if(BeanUtil.isNotEmpty(childPageBean.getData()) &&childPageBean.getData().size()>0){
                                childListDataMap.put(childViewlist.get(i).getId(),childPageBean.getData());
                                //setFieldValueByFieldName(childViewlist.get(i).getContainerField(),childPageBean.getData(),masterViewData,String.class,Object.class, List.class);
                                masterViewData.put(childViewlist.get(i).getContainerField(),childPageBean.getData());
                            }
                        }
                    }
                }
                String jsData=JSONObject.toJSONString(masterViewData);
                resultRestResponse = RestResponse.success().put("jsonData",jsData);
                //设置接口调用成功
                apiLog.setCallStatus("1");
            }

        }catch (Exception e){
            apiLog.setCallStatus("0");
            apiLog.setError("接入失败:"+e.getMessage());
            resultRestResponse =  RestResponse.error("接入失败:"+e.getMessage());
        }finally {
            //存储调用日志
            Date endDate = new Date();
            Long timeTotal = (endDate.getTime()-startDate.getTime());
            apiLog.setTotalTime(timeTotal);
            apiLog.setEndDate(endDate);
            formApiProducter.saveApiLog(apiLog);
        }
        return resultRestResponse;
    }
    /*
    *通过反射设置属性的值
    *@param fieldName 属性名
    * @param fieldValue 属性值
    *@param object 实体类对象
    * @param parameterTypes 设置属性值的类型
    * @throws
    * */

    public static void setFieldValueByFieldName(String fieldName,Object fieldValue,Object object,Class<?>... parameterTypes) {
        try{
            Field[] fields = object.getClass().getDeclaredFields();
            for(int i=0;i<fields.length;i++){
                Field field = fields[i];
                //字段名称
                String name = field.getName();
                if(name.equals(fieldName)){
                    field.setAccessible(true);
                    String methname = name.substring(0,1).toUpperCase()+name.substring(1);
                    Method m = object.getClass().getMethod("set" + methname,parameterTypes);
                    m.invoke(object,fieldValue);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 主数据申请
     * @param req
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/applyDatas")
    @ResponseBody
    public RestResponse applyMasterDatas(HttpServletRequest req, @RequestBody JSONObject jsonObject){
        log.info("viewId:"+req.getParameter("viewId"));
        String viewId = req.getParameter("viewId");
        if(StringUtil.isEmpty(viewId)){
            return  RestResponse.error("必传参数["+viewId+"]，值为空");
        }
        TokenModel tokenModel = getTokenModel();
//        ApiLog apiLog = new ApiLog();
//        apiLog.setViewId(viewId);
//        apiLog.setType("2");
//        apiLog.setThirdAppid(tokenModel.getThirdPartyAppId());
//        JSONObject params =getAllRequestParam(req);
//        apiLog.setJsonObject(params);
//        Date startDate = new Date();
//        apiLog.setStartDate(startDate);

        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setType("2");
        apiRequest.setViewId(viewId);
        apiRequest.setJsonObject(jsonObject);
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        return  formServer.saveAndChangeMasterByApi(apiRequest);
    }

    @PostMapping(value = "/saveOrUpdateMasterDatas")
    @ResponseBody
    public RestResponse saveOrUpdateMasterDatas(HttpServletRequest req, @RequestBody JSONObject jsonObject){
        log.info("viewId:"+req.getParameter("viewId"));
        String viewId = req.getParameter("viewId");
        if(StringUtil.isEmpty(viewId)){
            return  RestResponse.error("必传参数["+viewId+"]，值为空");
        }
        String dataId = req.getParameter("dataId");
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setType("23");
        apiRequest.setViewId(viewId);
        apiRequest.setJsonObject(jsonObject);
        TokenModel tokenModel = getTokenModel();
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        if(StringUtil.isNotEmpty(dataId)){
            apiRequest.setDataId(dataId);
        }
        return  formServer.saveAndChangeMasterByApi(apiRequest);
    }

    /**
     * 主数据修改
     * @param req
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/updateDatas")
    @ResponseBody
    public RestResponse updateMasterDatas(HttpServletRequest req, @RequestBody JSONObject jsonObject){
        String viewId = req.getParameter("viewId");
        String dataId = req.getParameter("dataId");
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setDataId(dataId);
        apiRequest.setType("3");
        apiRequest.setViewId(viewId);
        apiRequest.setJsonObject(jsonObject);
        TokenModel tokenModel = getTokenModel();
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        return  formServer.saveAndChangeMasterByApi(apiRequest);
    }

    /**
     * 主数据禁用
     * @param req
     * @param viewId
     * @param dataId
     * @return
     */
    @GetMapping(value = "/unenabledData")
    @ResponseBody
    public RestResponse unenabledMasterData(HttpServletRequest req, String viewId, String dataId){
        log.info("viewId:"+viewId);
        log.info("dataId:"+dataId);
        TokenModel tokenModel = getTokenModel();
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setDataId(dataId);
        apiRequest.setType("5");
        apiRequest.setViewId(viewId);

        FormApiStatus formApiStatus=new FormApiStatus();
        if(StringUtil.isNotEmpty(viewId)){
            formApiStatus.setViewId(viewId);
        }
        if(StringUtil.isNotEmpty(dataId)){
            formApiStatus.setDataId(dataId);
        }
        JSONObject jsonObject= JSON.parseObject(JSONObject.toJSONString(formApiStatus));
        apiRequest.setJsonObject(jsonObject);
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        return  formServer.dataStatusChangeByApi(apiRequest,"2");
    }

    /**
     * 主数据启用
     * @param req
     * @param viewId
     * @param dataId
     * @return
     */
    @GetMapping(value = "/enabledData")
    @ResponseBody
    public RestResponse enabledMasterData(HttpServletRequest req, String viewId, String dataId){
        log.info("viewId:"+viewId);
        log.info("dataId:"+dataId);

        TokenModel tokenModel = getTokenModel();
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setDataId(dataId);
        apiRequest.setType("4");
        apiRequest.setViewId(viewId);
        FormApiStatus formApiStatus=new FormApiStatus();
        if(StringUtil.isNotEmpty(viewId)){
            formApiStatus.setViewId(viewId);
        }
        if(StringUtil.isNotEmpty(dataId)){
            formApiStatus.setDataId(dataId);
        }
        JSONObject jsonObject= JSON.parseObject(JSONObject.toJSONString(formApiStatus));
        apiRequest.setJsonObject(jsonObject);
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        return  formServer.dataStatusChangeByApi(apiRequest,"1");
    }


    /**
     * 主数据删除
     * @param req
     * @param viewId
     * @param dataId
     * @return
     */
    @GetMapping(value = "/deleteMasterData")
    @ResponseBody
    public RestResponse deleteMasterData(HttpServletRequest req, String viewId, String dataId){
        log.info("viewId:"+viewId);
        log.info("dataId:"+dataId);
        TokenModel tokenModel = getTokenModel();
        ApiRequest apiRequest = new ApiRequest();
        apiRequest.setDataId(dataId);
        apiRequest.setType("6");
        apiRequest.setViewId(viewId);
        FormApiStatus formApiStatus=new FormApiStatus();
        if(StringUtil.isNotEmpty(viewId)){
            formApiStatus.setViewId(viewId);
        }
        if(StringUtil.isNotEmpty(dataId)){
            formApiStatus.setDataId(dataId);
        }
        JSONObject jsonObject= JSON.parseObject(JSONObject.toJSONString(formApiStatus));
        apiRequest.setJsonObject(jsonObject);
        if(BeanUtil.isNotEmpty(tokenModel)){
            apiRequest.setThirdAppid(tokenModel.getThirdPartyAppId());
        }
        return  formServer.dataStatusChangeByApi(apiRequest,"0");
    }
}
